import { Message } from 'element-ui'
import { saveAs } from 'file-saver'
import request, {get, post} from '../utils/request.js'
const imgSuffix = ["png", "jpg", "jpeg"];
const pdfSuffix = ["pdf"];

function checkSuffix(row, arr = []) {
  const { attachmentName } = row;
  const suffix = attachmentName.split(".").slice(-1)[0];
  return arr.includes(suffix);
}

const errorCode = {
  '401': '认证失败，无法访问系统资源',
  '403': '当前操作没有权限',
  '404': '访问资源不存在',
  'default': '系统未知错误，请反馈给管理员'
}

// 验证是否为blob格式
async function blobValidate(data) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}

// 上传文件
export const uploadFile = async (file)=>{
  let data = new FormData()
  data.append('files', file)
  return request({
    url: '/attachment/upload/file',
    method: 'post',
    data
  })
}

export function getAttachment(id) {
  return request({
    url: '/attachment/download/file/'+id ,
    method: 'get',
    responseType:'arraybuffer'
  })
}

export async function downloadAttachment(row) {
  let res = getAttachment(row.id)
  let isBlob = await blobValidate(res);
  if(isBlob){
    let blob = new Blob([res]);
    saveAs(blob, row.attachmentName)
  }else {
    const resText = await data.text();
    const rspObj = JSON.parse(resText);
    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
    Message.error(errMsg);
  }
}

export async function getFileUrl(row) {
  const { id } = row;
  const type = checkSuffix(row, imgSuffix) ? "img" : "pdf";
  let res = await getAttachment(id)
  let isBlob = await blobValidate(res);
  if(isBlob){
    const blob =
      type === "pdf"
        ? new Blob([res], { type: "application/pdf" })
        : new Blob([res]);
    const url = window.URL.createObjectURL(blob);
    return url
  } else {
    const resText = await data.text();
    const rspObj = JSON.parse(resText);
    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
    Message.error(errMsg);
  }
}
